import Vue from 'vue'
import VueRouter from 'vue-router'
//import Home from '@/views/Home.vue'
//import EditArticle from '@/components/EditArticle'
/*import Main from '@/views/Main.vue'
import ArticleDetail from '@/components/ArticleDetail'
import Category from '@/components/Category'
import Login from '@/views/Login'
import Admin from '@/views/Admin'
import CreateArticle from '@/components/CreateArticle'*/
const Home = () => import(/* webpackChunkName:"Home_Main" */ '@/views/Home.vue')
const Main = () => import(/* webpackChunkName:"Home_Main" */ '@/views/Main.vue')
const EditArticle = () => import( '@/components/EditArticle')
const ArticleDetail = () => import( '@/components/ArticleDetail')
const Category = () => import('@/components/Category')
const Login = () => import(/* webpackChunkName:"Login_Admin" */ '@/views/Login')
const Admin = () => import(/* webpackChunkName:"Login_Admin" */  '@/views/Admin')
const CreateArticle = () => import( '@/components/CreateArticle')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/home/main',
    children: [
      {
        path: 'main',
        component: Main
      }, {
        /**
         * 动态路由，实现的功能是当我们点击某一个文章的时侯，
         * 会跳转到文章的详细内容页面，这个时候需要把文章id给传过去。
         */
        path: 'article/detail/:id',
        component: ArticleDetail
      }
    ]
  },
  {
    path: '/article',
    name: 'Article',
    component: EditArticle
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }, {
    path: '/manager',
    name: 'Admin',
    component: Admin,
    redirect: '/manager/article/list',
    children: [
      {
        path: 'category',
        component: Category
      }, {
        path: 'article/list',
        component: Main
      }, {
        path: 'article/create',
        component: CreateArticle
      }, {
        path: 'article/edit/:id',
        component: CreateArticle
      }, {
        path: 'article/draft/list',
        component: Main
      }
    
    
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 路由导航守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from 从哪个路径访问
  // next 是放行函数 next() 放行， next('login')强制跳转到某一个页面
  // 获取token
  const tockenStr = window.localStorage.getItem('authToken');
  if (to.path === '/login') {
    // 即使是去登录页面，但是由于之前已经登录了，所以直接跳转到后端管理面
    if (tockenStr) {
      return next('/manager/article/list');
    } else {
      return next();
    }
  }
  
  // 用正则表达式进行匹配，凡是所有的以manager开头的路由，如果没有登录，就跳转到登录页面
  const pattern = /manager/
  if (!tockenStr && pattern.test(to.path)) return next('/login');
  next();
})
export default router
